package com.heima.article.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.common.minio.MinIOProperties;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Mr_Su
 * @version v1.0
 * @date 2022/7/4 21:36
 * @desciption
 */
@Service
@Slf4j
public class ArticleHtmlTasks {

    @Autowired
    private IApArticleContentService apArticleContentService;
    @Autowired
    private IApArticleService apArticleService;
    @Autowired
    private Configuration configuration;
    @Autowired
    private MinIOService minIOService;
    @Autowired
    private MinIOProperties minIOProperties;

    @Async
    public void createArticleHtml(ApArticle apArticle, String content) {
        try {
            // 给指定的一个文章生成静态页面
            Long articleId = apArticle.getId();

            // 1.获取准备好的模板
            Template template = configuration.getTemplate("article.ftl");
            // 2.准备数据 ap_article_content中的content属性
            List<Map> maps = JSON.parseArray(content, Map.class);


            Map dataModel = new HashMap();
            dataModel.put("content", maps);
            // 3.结合页面
            StringWriter writer = new StringWriter();
            template.process(dataModel, writer);
            // 4.上传到minio中
            ByteArrayInputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());
            minIOService.upload("/article/" + articleId + ".html", inputStream, "text/html");

            String staticUrl = minIOProperties.getEndpoint() + "/" + minIOProperties.getBucketName() +"/article/" + articleId + ".html";
            apArticle.setStaticUrl(staticUrl);
            apArticleService.updateById(apArticle);
        } catch (Exception e) {
            log.error("静态页面生成失败: " + apArticle.getId());
        }
    }
}
